﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Simhopp.Common
{
    public static class UserMap
    {
        public static int SaveUserToDatabase(User user)
        {
            user.CredentialsId = CredentialsMap.SaveCredentialsToDatabase(user.Credentials);
            return GenericMap.SaveObjectToDatabase(user);
        }

        public static void SaveUsersToDatabase(List<User> users)
        {
            foreach (var user in users)
                SaveUserToDatabase(user);
        }

        public static List<User> ReadAllUsersFromDataBase()
        {
            var dictionary = GenericMap.ReadAllObjectsFromDatabase(typeof(User));
            try
            {
                var users = dictionary.Select(User.GetFromDictionary).ToList();
                MyLogger.Debug("All dictionaries converted to User-objects");
                return users;
            }
            catch (Exception e)
            {
                MyLogger.Error("Could not convert all dictionaries to User-objects - " + e.Message);
                return null;
            }
        }

        public static User ReadJudgeFromDataBase(int id)
        {
            var dbResult = GenericMap.ReadObjectFromDatabase(id, typeof(User));
            return dbResult == null ? null : User.GetFromDictionary(dbResult);
        }

        public static void RemoveUserFromDataBase(User user)
        {
            CredentialsMap.RemoveCredentialsFromDatabase(user.Credentials);
            GenericMap.RemoveObjectFromDatabase(user);
        }
    }
}
